package com.fresher.dao;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;

import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.fresher.model.Accountinfo;
import com.fresher.model.User;
import com.fresher.model.UserRole;

@Repository
public class UserDao {
	

    @PersistenceContext
    private EntityManager entityManager;
    
    
    
    @Transactional
	public void updateUserPassword(String loginid,String newPassWord) {


			User user = entityManager.find(User.class,
					loginid);
			if (user == null) {
				throw new IllegalArgumentException("Unknown Employee id");
			}
			user.setPassword(newPassWord);
			// update
			entityManager.merge(user);

	}
    
    //create new user
    @Transactional
   	public boolean createNewUser(String userName, String passWord, String userRole) {
		boolean isAddSuccess=false;
		User user =new User();
		user = entityManager.find(User.class, userName);
		if (user == null) {
			isAddSuccess = true;
			User user1=new User(userName, passWord);
			user1.setEnabled((byte) 1);
    		entityManager.persist(user1);
    		createNewUserRole(userName,userRole);	
		}
    	return isAddSuccess;	
   	}
    
    //create new user role
    @Transactional
   	public void createNewUserRole(String userName, String userRole) {
    
    	UserRole userRolee=null;
    	if (null==userRole) {
			 userRolee=new UserRole("ROLE_USER");
		}else
    	if (userRole.equals("ROLE_ADMIN")) {
    		 userRolee=new UserRole(userRole);
		} 

    		User user = entityManager.getReference(User.class, userName);
        	userRolee.setUser(user);
    		entityManager.persist(userRolee);

   	}
    
  //view list user role
	@Transactional
	public List<UserRole> getUserRole(){
		
		// Obtains entity manager object


		// -----------Begin transaction-----------
		List<UserRole> UserRoleList=null;

			// Get a list of logs from DB
			TypedQuery<UserRole> query = entityManager
					.createQuery(
							"SELECT u FROM UserRole u",
							UserRole.class);
			

			UserRoleList = (List<UserRole>) query.getResultList();
			


		// -----------End transaction-----------

		return UserRoleList;
	}
	
	//view list user role
		@Transactional
		public boolean getUser(String username){
			boolean exist=false;
			// Obtains entity manager object
			// -----------Begin transaction-----------
			User User=null;
			User = entityManager.find(User.class, username);
			if (User != null) {
				exist = true;
			}
			return exist;
		}
}
